package nl.depository.pim.pages.admin;

import nl.depository.pim.pages.Dashboard;
import nl.depository.pim.services.DataService;

import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

public class Form
{
	private Object[] args;
	
	@Property(write=false)
	private String classSimpleName;

	private Class<?> beanClass;
	
	@Property
	private Object bean;
	
	@SuppressWarnings("unused")
	@Property(write=false)
	private BeanModel<?> beanModel;
	
	@Inject
	private DataService dataService;
	
	@Inject
	private BeanModelSource beanModelSource;
	
	@Inject
	private Messages messages;
	
	public void onActivate(Object[] args) throws Exception
	{
		this.args = args;
		
		if (args.length == 0)
		{
			throw new IllegalArgumentException("At least a entity class name should be given.");
		}
		
		classSimpleName = (String) args[0];
		beanClass = Class.forName("nl.depository.pim.entities." + classSimpleName);
		beanModel = beanModelSource.createEditModel(beanClass, messages);
		bean = args.length > 1
			? dataService.retrieveRecord((String) args[1])
			: beanClass.newInstance();
	}
	
	public Object[] onPassivate()
	{
		return args;
	}

	public String getId() throws Exception
	{
		return (String) beanClass.getDeclaredMethod("getId").invoke(bean);
	}
	
	public void onValidateForm()
	{
		dataService.save(bean);
	}
	
	public Object onSuccess()
	{
		return Dashboard.class;
	}
}
